package org.edu.modules.dorm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.dorm.entity.VeDormManager;
import org.edu.modules.dorm.entity.VeDormSSLou;
import org.edu.modules.dorm.entity.VeFileFiles;
import org.edu.modules.dorm.entity.bo.BasicResponseBO;
import org.edu.modules.dorm.entity.bo.VeCampusBO;
import org.edu.modules.dorm.service.*;
import org.edu.modules.dorm.vo.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "宿舍楼信息管理")
@RestController
@RequestMapping("dorm/bulidMng")
@Slf4j
public class VeDormSSLouController extends BaseController<VeDormSSLou, VeDormSSLouService> {

    @Autowired
    private VeDormSSLouService veDormSSLouService;
    @Autowired
    private VeDormManagerService veDormManagerService;
    @Autowired
    private VeBaseTeacherService veBaseTeacherService;
    @Autowired
    private VeDormGetManagerService veDormGetManagerService;
    @Autowired
    private VeBaseDormManageService veBaseDormManageService; //李少君

    @Value("${edu.path.upload}")
    private String upLoadPath;

    //添加宿舍楼
    @AutoLog(value = "宿舍楼管理-添加宿舍楼")
    @ApiOperation(value = "添加宿舍楼", notes = "宿舍管理楼-添加宿舍")
    @PostMapping(value = "/addSuSheLou")

    public Result<?> addSuSheLou(
            @ApiParam("建筑物号") @RequestParam(value = "jzwh") String jzwh,
            @ApiParam("建筑物名称") @RequestParam(value = "jzwmc") String jzwmc,
            @ApiParam("校区号") @RequestParam(value = "xqh",required = false) Long xqh,
            @ApiParam("性别码") @RequestParam(value = "xbm",required = false) Integer xbm,
            @ApiParam("建筑物层数") @RequestParam(value = "jzwcs",required = false) Integer jzwcs,
            @ApiParam("总建筑面积") @RequestParam(value = "zjzmj",required = false) Integer zjzmj,
            @ApiParam("总使用面积") @RequestParam(value = "zsymi",required = false) Integer zsymj,
            @ApiParam("建筑物地址") @RequestParam(value = "jzwdz") String jzwdz,
            @ApiParam("建筑物状况码") @RequestParam(value = "jzwzkm") String jzwzkM,
            @ApiParam("建筑物图片") @RequestParam(value = "jzwtp",required = false) Integer jzwtp,
            @ApiParam("建筑物平面图") @RequestParam(value = "jzwpmt",required = false) Integer jzwpmt,
            @ApiParam("排序") @RequestParam(value = "listSort",required = false) Integer listSort,
            @ApiParam("图片地址") @RequestParam(value = "fileUrl",required = false) String fileUrl,
            @ApiParam("姓名") @RequestParam(value = "name",required = false) String name,
            @ApiParam("尺寸") @RequestParam(value = "size",required = false) Long size
    ) {

        QueryWrapper<VeDormSSLou> wrapper=new QueryWrapper<>();
        wrapper.eq("jzwmc",jzwmc);
        VeDormSSLou ssl=veDormSSLouService.getOne(wrapper);
        if (ssl!=null){
            return Result.OK("添加失败，该宿舍楼已经存在");
        }
        VeDormSSLou veDormSuSheLou = new VeDormSSLou();
        VeFileFiles fileFiles = new VeFileFiles();
        String[] arr = name.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equals("jpg") && !suffixName.equals("png") && !suffixName.equals("") ) {
            return Result.error(400, "文件类型不能上传");
        }
        fileFiles.setExt(suffixName);
        fileFiles.setName(name);
        fileFiles.setSize(size);
        fileFiles.setSourcefile(fileUrl);
        fileFiles.setCreatetime(System.currentTimeMillis() / 1000);
        veDormSuSheLou.setJzwmc(jzwmc);
        veDormSuSheLou.setJzwh(jzwh);
        veDormSuSheLou.setXqh(xqh);
        veDormSuSheLou.setXbm(xbm);
        veDormSuSheLou.setZjzmj(zjzmj);
        veDormSuSheLou.setJzwdz(jzwdz);
        veDormSuSheLou.setListsort(listSort);
        veDormSuSheLou.setJzwcs(jzwcs);
        veDormSuSheLou.setZsymj(zsymj);
        veDormSuSheLou.setJzwzkm(jzwzkM);
        veDormSuSheLou.setJzwtp(jzwtp);
        veDormSuSheLou.setJzwpmt(jzwpmt);

        Integer save = veDormSSLouService.addSSL(veDormSuSheLou, fileFiles);
        return Result.OK("宿舍楼添加成功");
    }

    //通过宿舍楼名称进行模糊查询
    @AutoLog(value = "宿舍楼管理-宿舍楼查询")
    @ApiOperation(value = "宿舍楼查询", notes = "宿舍管理楼-宿舍楼查询")
    @PostMapping(value = "/querySuSheLou")
    public Result<?> querySuSheLou(@RequestParam(value = "jzwmc") String jzwmc) {
//        BasicResponseBO<List> list = veBaseDormManageService.getCampusMessage(); //李少君
//        List<VeCampusBO> result = JSONObject.parseArray(JSON.toJSONString(list.getResult()),VeCampusBO.class);
//        List<VeDormSSLouVo> v = veDormSSLouService.selectByParam(jzwmc);
//        for(int i =0 ;i<v.size();i++){
//            for (int j =0 ;j<result.size();j++){
//                if(v.get(i).getXqh()==(result.get(j).getId().longValue())){
//                    v.get(i).setXqmc(result.get(j).getXqmc());
//                }
//            }
//        }
        List<VeDormSSLouVo> list = veDormSSLouService.selectByParam(jzwmc);
        return Result.OK(list);

    }

    //宿舍楼导出功能
    @AutoLog(value = "宿舍管理-导出功能")
    @ApiOperation(value = "导出功能", notes = "宿舍管理-宿舍导出")
    @PostMapping(value = "/exportSuSheLou")
    public Result<?> exportSuSheLou(@RequestParam(name = "id", required = true) Integer id) {
        VeDormSSLou veDormSuSheLou = veDormSSLouService.getById(id);
        if (veDormSuSheLou == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(veDormSuSheLou);
    }

    //宿舍楼编辑
    @AutoLog(value = "宿舍楼管理-编辑宿舍楼")
    @ApiOperation(value = "编辑宿舍楼", notes = "宿舍管理楼-编辑宿舍楼")
    @PostMapping(value = "/editSuSheLou")
    public Result<?> editSuSheLou(
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "jzwh") String jzwh,
            @RequestParam(value = "jzwmc") String jzwmc,
            @RequestParam(value = "xqh") Long xqh,
            @RequestParam(value = "xbm") Integer xbm,
            @RequestParam(value = "jzwcs") Integer jzwcs,
            @RequestParam(value = "zjzmj") Integer zjzmj,
            @RequestParam(value = "zsymi") Integer zsymj,
            @RequestParam(value = "jzwdz") String jzwdz,
            @RequestParam(value = "jzwzkm") String jzwzkM,
            @RequestParam(value = "jzwtp") Integer jzwtp,
            @RequestParam(value = "jzwpmt") Integer jzwpmt,
            @RequestParam(value = "listSort") Integer listSort,
            @RequestParam(value = "fileUrl") String fileUrl,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "size") Long size
    ) {

        VeDormSSLou veDormSuSheLou = new VeDormSSLou();

        VeFileFiles fileFiles = new VeFileFiles();
        //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
        String[] arr = name.split("\\.");
        //获取文件后缀名
        String suffixName = arr[arr.length - 1];
        if (!suffixName.equals("jpg") && !suffixName.equals("png") && !suffixName.equals("") ) {
            return Result.error(400, "文件类型不能上传");
        }
        fileFiles.setExt(suffixName);
        fileFiles.setName(name);
        fileFiles.setSize(size);
        fileFiles.setSourcefile(fileUrl);
        fileFiles.setCreatetime(System.currentTimeMillis() / 1000);

        veDormSuSheLou.setId(id);
        veDormSuSheLou.setJzwmc(jzwmc);
        veDormSuSheLou.setJzwh(jzwh);
        veDormSuSheLou.setXqh(xqh);
        veDormSuSheLou.setXbm(xbm);
        veDormSuSheLou.setZjzmj(zjzmj);
        veDormSuSheLou.setJzwdz(jzwdz);
        veDormSuSheLou.setListsort(listSort);
        veDormSuSheLou.setJzwcs(jzwcs);
        veDormSuSheLou.setZsymj(zsymj);
        veDormSuSheLou.setJzwzkm(jzwzkM);
        veDormSuSheLou.setJzwtp(jzwtp);
        veDormSuSheLou.setJzwpmt(jzwpmt);
        veDormSSLouService.editSSL(veDormSuSheLou, fileFiles);
        return Result.OK();
    }

    //宿舍删除功能
    @AutoLog(value = "宿舍楼管理-宿舍楼删除")
    @ApiOperation(value = "宿舍楼删除", notes = "宿舍楼管理-宿舍删除")
    @PostMapping(value = "/deleteSuSheLou")
    public Result<?> deleteSuSheLou(@RequestParam(name = "id", required = true) Integer id) {
        veDormSSLouService.removeById(id);
        return Result.OK("删除成功");
    }

    //获取已添加的宿舍管理员
    @AutoLog(value = "宿舍楼管理-获取宿舍管理员")//李少君
    @ApiOperation(value = "获取宿舍管理员", notes = "宿舍管理-获取宿舍管理员")
    @PostMapping(value = "/showMng")
    public Result<?> showMng(@RequestParam(value = "sslId") Integer sslId) {
        VeDormManagerVo manage = veDormGetManagerService.showMng(sslId);
        if(manage==null){
            VeDormManagerVo v = new VeDormManagerVo();
            return Result.OK("请添加管理员",v);
        }
        else {
            return Result.OK(manage);
        }
    }

    //添加宿舍管理员
    @AutoLog(value = "宿舍楼管理-添加宿舍管理员")
    @ApiOperation(value = "添加宿舍管理员", notes = "宿舍管理-添加宿舍管理员")
    @PostMapping(value = "/addMng")
    public Result<?> addMng(@RequestParam(value = "userId") Integer userId,
                            @RequestParam(value = "sslId") Integer sslId
    ) {
        VeDormManagerVo manage = veDormGetManagerService.showMng(sslId);//李少君
        if(manage==null){//李少君
            VeDormManager veDormManager = new VeDormManager();
            veDormManager.setSslId(sslId);
            veDormManager.setUserId(userId);
            veDormManagerService.save(veDormManager);
            return Result.OK();
        }else{//李少君
//            VeDormManager veDormManager = new VeDormManager();
//            veDormManager.setSslId(sslId);
//            veDormManager.setUserId(userId);
//            veDormManagerService.updateById(veDormManager);
            veDormGetManagerService.updateAdminId(sslId, userId);
            return Result.OK();
        }

    }
    @AutoLog(value = "宿舍楼管理-通过id修改信息")
    @ApiOperation(value = "通过id获取修改信息", notes = "宿舍管理-通过id获取修改信息")
    @PostMapping(value = "/updateMessage")

    public Result<?> updateMessage(@RequestParam(value = "id") Long id

    ) {

        return Result.OK(veDormSSLouService.getEditInfo(id));
    }

    @AutoLog(value = "宿舍楼信息导出excel表格")
    @ApiOperation(value = "宿舍楼信息导出excel表格", notes = "宿舍楼管理—宿舍楼信息导出excel表格")
    @RequestMapping(value = "export")
    public ModelAndView excelExport( @RequestParam(value = "jzwmc",required = false) String jzwmc ) {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<VeDormSSLouVo> list = veDormSSLouService.selectByParam(jzwmc);
//        BasicResponseBO<List> list1 = veBaseDormManageService.getCampusMessage(); //李少君
//        List<VeCampusBO> result = JSONObject.parseArray(JSON.toJSONString(list1.getResult()),VeCampusBO.class);
//        List<VeDormSSLouVo> list = veDormSSLouService.selectByParam(jzwmc);
//        for(int i =0 ;i<list.size();i++){
//            for (int j =0 ;j<result.size();j++){
//                if(list.get(i).getXqh()==(result.get(j).getId().longValue())){
//                    list.get(i).setXqmc(result.get(j).getXqmc());
//                }
//            }
//        }
        List<VeDOrmSSLouExcelVo> excelList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            VeDOrmSSLouExcelVo excelVo=new VeDOrmSSLouExcelVo();
            excelVo.setId(list.get(i).getId());
            excelVo.setJzwh(list.get(i).getJzwh());
            excelVo.setJzwmc(list.get(i).getJzwmc());
            Integer xbm=list.get(i).getXbm();
            String xb=null;
            if (xbm==0){
                xb="混住宿舍楼";
            } else if (xbm==1){
                xb="男生宿舍楼";
            } else if (xbm==2){
                xb="女生宿舍楼";

            }
          excelVo.setXb(xb);
            excelVo.setJzwcs(list.get(i).getJzwcs());
            excelVo.setZjzmj(list.get(i).getZjzmj());
            excelVo.setJzwdz(list.get(i).getJzwdz());
            excelVo.setListSort(list.get(i).getListSort());
            excelVo.setXqmc(list.get(i).getXqmc());
            Integer status=list.get(i).getStatus();
            String state=null;
            if (status==0){
                state="正常使用";
            }
            else if (status==1){
                state="维修";
            }
            else if (status==2){
                state="清空";
            }
            excelVo.setState(state);
            excelList.add(excelVo);
        }

        mv.addObject(NormalExcelConstants.FILE_NAME, "宿舍楼");
        mv.addObject(NormalExcelConstants.CLASS, VeDOrmSSLouExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("宿舍楼", "导出人:" + user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelList);
        return mv;
    }


    @AutoLog(value = "宿舍楼信息导出excel模板")
    @ApiOperation(value = "宿舍楼信息导出excel模板", notes = "宿舍楼管理—宿舍楼信息导出excel模板")
    @RequestMapping(value = "exportModel")
    public ModelAndView exportModel() {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "宿舍楼列表");
        mv.addObject(NormalExcelConstants.CLASS, VeDOrmSSLouExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("宿舍楼列表数据", "导出人:" + user.getRealname(), "导出信息");
        List<VeDOrmSSLouExcelVo> list = new ArrayList<>();//李少君
        VeDOrmSSLouExcelVo v = new VeDOrmSSLouExcelVo();
        v.setJzwmc("学生公寓");
        v.setXb("男生宿舍楼");
        v.setJzwh("C1");
        v.setXqmc("南校区");
        v.setJzwcs(5);
        v.setZjzmj(5000);
        v.setJzwdz("南校区1号");
        v.setListSort(1);
        v.setState("正常使用");
        list.add(v);//李少君
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
//        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<VeDOrmSSLouExcelVo>());李少君
        mv.addObject(NormalExcelConstants.DATA_LIST, list);//李少君
        return mv;
    }

    @AutoLog(value = "宿舍楼信息导入excel表格")
    @ApiOperation(value = "宿舍楼信息导入excel表格", notes = "宿舍楼管理—宿舍楼信息导入excel表格")
    @PostMapping(value = "import")
    public Result<?> excelImport( MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(2);
        params.setHeadRows(1);
        params.setNeedSave(true);
        try {
            List<VeDOrmSSLouExcelVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeDOrmSSLouExcelVo.class, params);

            veDormSSLouService.excelImport(list);
            return Result.OK();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("文件导入失败:" + e.getMessage());
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        return super.importExcel(httpServletRequest, httpServletResponse, VeDormSSLou.class);
    }

    //宿舍管理员查询
  @ApiOperation(value = "宿舍管理员查询", notes = "宿舍管理员查询")
  @PostMapping(value = "teacherMessage")
  public List<VeBaseTeacherVo> teacherMessage(){
//      BasicResponseBO<List> list = veBaseDormManageService.getTeacherMessage(); //李少君
//      List<VeBaseTeacherVo> result = list.getResult();
//
//      return result;
      return veBaseTeacherService.teacherMessage();
  }

  //发送性别码
  @ApiOperation(value = "发送性别码", notes = "发送性别码")
  @PostMapping(value = "sexNum")
  public Result<?> findSex(@RequestParam("buildId")Long buildId){
      VeDormSSLou veDormSSLou = veDormSSLouService.getById(buildId);
      Integer sex = veDormSSLou.getXbm();
      return Result.OK(sex);
  }
}
